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nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ;
		
	$("#header").append(space).append("<button class=\"button\" id=\"logoutButton\" " +
		"style=\"text-align: left;font-size:16px;color:#770099;background-color:#FFFFFF;\"> log out</button>");	

		
		$("#header button#logoutButton").click(function() {
			$.cookie("first",null) ;
			$.cookie("logged",false) ;
			login() ;
		 });


var primaryAttributes = [];
var secondaryAttributes = [];
var thirdyAttributes = [];
    		
 
var create = function() { 
	var params = {first:primaryAttributes, second:secondaryAttributes,third:thirdyAttributes };
	console.info(params) ;
	Refine.postProcess(
      "okkam-extension",
      "createToENS",
      params,
      {},{},
      { 
          "onDone": function(response) {
    	  alert(response["key"]);
    	 }
      }
  );
}

var uploadTDB = function(tdbStore, namedGraph) { 
	var params = {rdfStore:tdbStore, graph:namedGraph};
  Refine.postProcess(
      "okkam-extension",
      "uploadtoTDB",
      params,
      {},{},
      { 
          "onDone": function(response) {
    	  alert(response["key"]);
    	 }
      }
  );
}

var update = function() { 
  Refine.postProcess(
      "okkam-extension",
      "updateEntitiesToENS",
      params = {},
      {},{},
      { 
          "onDone": function(response) {
    	  alert(response["key"]);
    	 }
      }
  );
}


var countUpdate = function() { 
  Refine.postProcess(
      "okkam-extension",
      "countEntities",
      params = {},
      {},{},
      { 
          "onDone": function(response) {
    	  alert(response["key"]+" Entities are to be Updated!!!");
    	  
    	 }
      }
  );
}


var countCreate = function() { 
  Refine.postProcess(
      "okkam-extension",
      "countEntities",
      params = {},
      {},{},
      { 
          "onDone": function(response) {
    	  	alert(response["key"]+" Entities are to be created!!!");
    	     	  	
    		var dialog = $(DOM.loadHTML("okkam-extension", "html/attributes.html"));

    		var elmts = DOM.bind(dialog);	
  
    		elmts.dialogHeader.text("Selecting Primary, Secondary and Third level mathcing features to create Entities...");
    		var level = DialogSystem.showDialog(dialog);
    		var attributes = response["attributes"];
    	  	$.each(attributes , function(i, val) { 
    	    elmts.propListPrimary.append('<input type="checkbox" value="'+attributes [i]+'" /> ' + attributes [i] + '<br />');
    	    elmts.propListsecondary.append('<input type="checkbox" value="'+attributes [i]+'"  /> ' + attributes [i] + '<br />');
    	    elmts.propListThird.append('<input type="checkbox" value="'+attributes [i]+'"  /> ' + attributes [i] + '<br />');
    	  });
    	  

    	  	elmts.okButton.click(function() {
    	  		//reinitailize every time
        	  	primaryAttributes = [];
        	  	secondaryAttributes = [];
        	  	thirdyAttributes = [];
    	  		elmts.propListPrimary.children("input:checkbox:checked").each(function(i,value){ 
    	  			primaryAttributes.push(value.value) ;
    			 });	 
    	  			elmts.propListsecondary.children("input:checkbox:checked").each(function(i,value){ 
    	  			secondaryAttributes.push(value.value) ;
    			 });
    	  			elmts.propListThird.children("input:checkbox:checked").each(function(i,value){ 
    	  			thirdyAttributes.push(value.value) ;
    			 });
    	 	DialogSystem.dismissUntil(level - 1); 
		 });    	  	 	  

    	 }
      }
  );
}

ExporterManager.handlers.showUploaderDialog = function() {
	countCreate();
	var dialog = $(DOM.loadHTML("okkam-extension", "html/create-dialog.html"));

	 var elmts = DOM.bind(dialog);
	 elmts.dialogBody.text("ENS Entity Create");

	 	var level = DialogSystem.showDialog(dialog);
	 	
	 	elmts.uploadButton.click(function() {
		
	 		create();
	 		DialogSystem.dismissUntil(level - 1);  
		 });
	 elmts.cancelButton.click(function() {
	     DialogSystem.dismissUntil(level - 1);
	  });
};


ExporterManager.handlers.showUploaderTDBDialog = function() {	
	
	var dialog = $(DOM.loadHTML("okkam-extension", "html/uploader-TDB-dialog.html"));

	 var elmts = DOM.bind(dialog);
	 
	 		var today=new Date();
	 		var todaymonth = today.getMonth()+1 ;
	 		if(todaymonth < 10)
	 			todaymonth = "0" +todaymonth;
	 		var todayday = today.getDate() ;
	 		if(todayday < 10)
	 			todayday = "0"+ todayday ;
	 		
	 			for (var i=1; i<=31; i++){
	 			if(i<10)
	 				elmts.daydropdown.append(new Option("0"+i,"0"+i));
	 			else
	 				elmts.daydropdown.append(new Option(i,i));
	 			}
	 			elmts.daydropdown.val(todayday, todayday) ;
	 			
 				for (var i=1; i<=12; i++){
 				if(i<10)
 					elmts.monthdropdown.append(new Option("0"+i,"0"+i));
 				else
 					elmts.monthdropdown.append(new Option(i,i));
 				}
	 			elmts.monthdropdown.val(todaymonth, todaymonth) ;
 				
	 			
 				for (var i=today.getFullYear()-10; i<=today.getFullYear(); i++){
 					elmts.yeardropdown.append(new Option(i, i));
 				}
 				elmts.yeardropdown.val(today.getFullYear(), today.getFullYear()) ;
	 
 				elmts.yeardropdown.change(function(e) {
 					alert(elmts.yeardropdown.val()); 
 					});
			
 			elmts.dialogHeader.text("Uploading RDF to TDB through Fuseki...");
	 	
		 	var level = DialogSystem.showDialog(dialog);
		 	
		 	//Geting service End points
		 	elmts.getServiceEndPoint.click(function() {
		 		elmts.serviceEndPoints.empty() ;
		 		if(elmts.serverAddress.val() == ""){
		 			alert("Please Enter the server address") ;
		 			elmts.serverAddress.focus() ;
		 		}
		 		else
		 		$.ajax({
				    type: "GET",
				    url: elmts.serverAddress.val()+"/uploadToTDB?callback=?",
				    data: {},
				    dataType: "json",
				    success: function (response) {	
					    $.each(response, function(i, item) {
					    	elmts.serviceEndPoints.append(new Option(response[i], response[i]));
					    });
				    }
	 			});
		 	});
		 	
		 	//Geting data sets
		 	elmts.serviceEndPoints.change(function() { 
		 		elmts.dataSets.empty() ;
		 		elmts.graphNames.empty() ;
		 		if(elmts.serverAddress.val() == ""){
		 			alert("Please Enter the server address") ;
		 		}
		 		else if (elmts.serviceEndPoints.val() == ""){
		 			alert("Please Select Service End Points") ;
		 			}
		 			else
		 		$.ajax({
				    type: "GET",
				    url: elmts.serverAddress.val()+"/uploadToTDB?callback=?",
				    data: {serviceEndPoint:elmts.serviceEndPoints.val()},
				    dataType: "json",
				    success: function (response) {	
					    $.each(response, function(i, item) {
					    	elmts.dataSets.append(new Option(response[i], response[i]));
					    });
				    }
	 			});
		 		
		 	});
	 	
		 	//Geting graph names
		 	elmts.dataSets.change(function() { 
		 		elmts.graphNames.empty() ;
		 		if(elmts.serverAddress.val() == ""){
		 			alert("Please Enter the server address") ;
		 		}
		 		else if (elmts.dataSets.val() == ""){
		 			alert("Please Select Service End Points") ;
		 			}
		 			else
		 		$.ajax({
				    type: "GET",
				    url: elmts.serverAddress.val()+"/uploadToTDB?callback=?",
				    data: {service:elmts.serviceEndPoints.val()+elmts.dataSets.val()+"/query"},
				    dataType: "json",
				    success: function (response) {	
					    $.each(response, function(i, item) {
					    	elmts.graphNames.append(new Option(response[i], response[i]));
					    });
				    }
	 			});
		 		
		 	});
		 	
		 	//upload to TDB store
		 	elmts.uploadButton.click(function() {
		 		if(elmts.serviceEndPoints.val() == "" && elmts.dataSets.val() == ""){
		 			alert("Please select Rdf Store and Data Sets")
		 		}
		 		else if(elmts.dataSpace.val()!="" && elmts.provenance.val()!=""){
		 			var namedGraph = elmts.dataSpace.val() + elmts.dataSets.val()+"/" + elmts.provenance.val() +
		 			"/"+elmts.yeardropdown.val() +"/" + elmts.monthdropdown.val() + "/" +elmts.daydropdown.val();
		 			var tdbStore = elmts.serviceEndPoints.val()+"/"+elmts.dataSets.val()+"/update" ;
			 		uploadTDB(tdbStore, namedGraph);
			 		DialogSystem.dismissUntil(level - 1);  
		 		}
		 		else {
			 		var namedGraph = elmts.graphNames.val();
			 		var tdbStore = elmts.serviceEndPoints.val()+"/"+elmts.dataSets.val()+"/update" ;
			 		uploadTDB(tdbStore, namedGraph);
			 		DialogSystem.dismissUntil(level - 1); 
		 		}
			 });
		 	//cancel operations
		 elmts.cancelButton.click(function() { 
		     DialogSystem.dismissUntil(level - 1);
		  });
		 // clear contenst
		 elmts.clearButton.click(function() { 
		    elmts.graphNames.empty() ;
		    elmts.dataSets.empty() ;
		    elmts.serviceEndPoints.empty() ;
		  });
		  
	 };

ExporterManager.handlers.showUpdaterDialog = function() {
	countUpdate();
	var dialog = $(DOM.loadHTML("okkam-extension", "html/update-dialog.html"));

	 var elmts = DOM.bind(dialog);
	 elmts.dialogBody.text("ENS Entity Updater");

	 	var level = DialogSystem.showDialog(dialog);
	 	
	 	elmts.uploadButton.click(function() {
		
	 		update();
	 		DialogSystem.dismissUntil(level - 1);  
		 });
	 elmts.cancelButton.click(function() {
	     DialogSystem.dismissUntil(level - 1);
	  });
	 
};

$(function() {
	ExtensionBar.MenuItems.push({
		"id" : "okkam", //uploadtoENS
		"label" : "OKKAM",
		"submenu" : [ 
		              {
			"id" : "Okkam-storage-create",
			label : "Create Entities to OKKAM ENS...",
			click : function() { ExporterManager.handlers.showUploaderDialog(); }
			},
			{},
			{
				"id" : "Okkam-storage-update",
			label : "Update Entities to OKKAM ENS...",
			click : function() { ExporterManager.handlers.showUpdaterDialog(); }	
			},
			{},
			{
				"id" : "Okkam-TDB-update",
			label : "Upload RDF dataset to TDB...",
			click : function() { ExporterManager.handlers.showUploaderTDBDialog(); }	
			}
			 ]
	});
}); 


DataTableColumnHeaderUI.extendMenu(function(column, columnHeaderUI, menu) {
   
    var DelteOkkamIds = function() { 
        params = { "column_name": column.name };
        body = {};
        updateOptions = {};
        callbacks = { 
            "onDone": function(response) {
        	alert(response["key"]);
            }
        }

        Refine.postProcess(
            "okkam-extension",
            "deleteByOkkamId",
            params,
            body,
            updateOptions,
            callbacks
        );
    }

    MenuSystem.insertAfter(
        menu,
        [ "core/edit-column" ],
        {
            id: "delteOkkamId",
            label: "Delete From ENS",
            click: DelteOkkamIds 
        }
    );
});



DataTableColumnHeaderUI.extendMenu(function(column, columnHeaderUI, menu) {

	    var doCFDialog = function(response) {
	    	
        var dialog = $(DOM.loadHTML("okkam-extension", "html/CFdialog.html"));
    
        var elmts = DOM.bind(dialog);
        elmts.dialogHeader.text("Codice Fisicale Validation Result for Column \"" + column.name + "\"");
        var result;
       // alert(response["CF"]); 
       elmts.dialogBody.html(" <pre> Wrong Codice Fiscale <br>"+response["CF"]+"</pre>");

        var level = DialogSystem.showDialog(dialog);

        elmts.okButton.click(function() {
            DialogSystem.dismissUntil(level - 1);
        }); 
    };

    
    var ValidateCF = function() { 
        params = { "column_name": column.name };
        body = {};
        updateOptions = {};
        callbacks = { 
            "onDone": function(response) {
        	doCFDialog(response);
            }
        }

        Refine.postProcess(
            "okkam-extension",
            "ValidateCodiceFiscale",
            params,
            body,
            updateOptions,
            callbacks
        );
        
    }

   MenuSystem.insertAfter(
        menu,
        [ "core/edit-column" ],
        {
            id: "ValidateCF",
            label: "Validate Fiscal Code",
            click: ValidateCF 
        }
    );
});



DataTableColumnHeaderUI.extendMenu(function(column, columnHeaderUI, menu) {

	    var doPartitaIVADialog = function(response) {
	    	
        var dialog = $(DOM.loadHTML("okkam-extension", "html/partitaIVADialog.html"));
    
        var elmts = DOM.bind(dialog);
        elmts.dialogHeader.text("PartitaIVA Validation Result for Column \"" + column.name + "\"");
        var result; 
       elmts.dialogBody.html(" <pre> Wrong PartitaIVA <br>"+response["partitaIVA"]+"</pre>");

        var level = DialogSystem.showDialog(dialog);

        elmts.okButton.click(function() {
            DialogSystem.dismissUntil(level - 1);
        }); 
    };

    
    var ValidatePartitaIVA = function() { 
        params = { "column_name": column.name };
        body = {};
        updateOptions = {};
        callbacks = { 
            "onDone": function(response) {
        	doPartitaIVADialog(response);
            }
        }

        Refine.postProcess(
            "okkam-extension",
            "ValidatePartitaIVA",
            params,
            body,
            updateOptions,
            callbacks
        );
        
    }

   MenuSystem.insertAfter(
        menu,
        [ "core/edit-column" ],
        {
            id: "ValidatePartitaIVA",
            label: "Validate P.IVA",
            click: ValidatePartitaIVA 
        }
    );
});



//Export RDF dataset as TRIG format....

ExporterManager.MenuItems.push(
		{
			"id" : "exportRdfTrig",
          	"label":"RDF as Trig",
          	click:   function() { RdfTRIGExporterMenuBar.exportRDFTRIG(); }
		}
);


RdfTRIGExporterMenuBar = {};
RdfTRIGExporterMenuBar.exportRDFTRIG = function() {
		
    if (!theProject.overlayModels.rdfSchema) {
        alert(
            "You haven't done any RDF schema alignment yet!"
        );
    } else {
    
    	var dialog = $(DOM.loadHTML("okkam-extension", "html/export-dialog.html"));
    	
		var elmts = DOM.bind(dialog);
		//elmts.dialogBody.text("RDF dataset Trig Exporter");
		
			var level = DialogSystem.showDialog(dialog);
			
			elmts.exportButton.click(function() { 
				if(elmts.txtGraph.val() ==""){
					alert("Please Enter the graph name")
				} else if(!(elmts.txtGraph.val().search('http://')>=0)){
					alert("Graph name should start with 'http://' !!!")
				} else {
			      Refine.postProcess(
			      "okkam-extension",
			      "ExportAsTrig",
			      params = {"graph":elmts.txtGraph.val()},
			      {},{},
			      	{ 
			          "onDone": function(response) {
				    	  alert(response["key"]);
					    	 }
				    }
			  );
			
				DialogSystem.dismissUntil(level - 1); 
			          }
			 });
		elmts.cancelButton.click(function() {
		    DialogSystem.dismissUntil(level - 1);
		 });
    }
  };
	
	
   
       if ($.cookie("logged") == false){ 
    	   login();
       }// logout expires
       function login ()	{
		
		var dialog = $(DOM.loadHTML("okkam-extension", "html/login.html"));
		var elmts = DOM.bind(dialog);
	
	 	elmts.dialogHeader.text("Login to Google Refine");
	 	var level = DialogSystem.showDialog(dialog);
	
		elmts.username.focus();
		
		
		elmts.dialogHeader.css("text-align","center");
		elmts.dialogBody.css("text-align","center");
		
		
	 	elmts.loginButton.click(function() {
	 		
	 		$.ajax({
				    type: "GET",
				    url: "http://192.168.234.122:9080//okkamrefine/login?callback=?",
				    data: {grusername:elmts.username.val(),grpassword:elmts.password.val()},
				    dataType: "json",
				    timeout: 1000,
				    success: function (response) {	
				    	if(elmts.password.val()==response["password"]){
				    		 $.cookie("first",false) ;
				    		 $.cookie("logged",true) ;
				    		DialogSystem.dismissUntil(level - 1);
				    	} 
				    	else
				    		alert (response["password"]);
				    }
	 			});	 	
	 });
	 	
	 	   elmts.password.keypress(function(e) {
	        if(e.which == 13) {
	            elmts.loginButton.focus().click();
	        }
	    });
	 	
	 	 	elmts.cancelButton.click(function() {
	 	 		$('div').hide();
	 }); 	
	 }
        		if($.cookie("first") == null){
        			login ();
			}
		    // Initialize the activity check
		    	$.activity.init({
		        // Set interval check to every 60 seconds
		        interval: 1000*60,
		        intervalFn: function(info){
		            console.log('Interval Check - Last Active:', info.lastActive, ', Difference in milliseconds to current time:', info.diff);
		        },
		        // Set inactive check to every 20 mnts
		        inactive: 1000*60*20,
		        inactiveFn: function(){
		        	 $.cookie("first",null) ;
		        	 $.cookie("logged",false) ;
		        	login ();
		        	}
		    	});
		
		    // Either reactivate, or update the current timestamp when user clicks on the page
		    $(document).click(function(){
		        if ( $.activity.isActive() )
		            $.activity.update();
		        else
		            $.activity.reActivate();
		    });
       // } //else -  logout
});
});